const http = require('http')
const fs = require('fs')

const server = http.createServer(function (req, res) {
  //获取文件类型
  var type = req.url.substr(req.url.length - 4, req.url.length)

  //获取资源路径
  var realpath = __dirname
  console.log(realpath)

  //加载需要显示的图片资源
  if (type == '.jpg' || type == '.png') {
    res.writeHead(200, { 'Content-Type': 'text/' + type })
    res.end(fs.readFileSync(realpath + 'a.jpg'))
  }

  // 加载首页
  var filePath = 'index.html'
  fs.stat(filePath, function (error, data) {
    if (error) {
      res.writeHead(404)
      res.end('404 Not Found.')
    } else {
      res.writeHead(200)
      fs.createReadStream(filePath).pipe(res)
    }
  })
})

server.listen(3001, 'localhost', () => {
  console.log(`Server running at http://localhost:3001/`)
})
